<?php
/**
 * Адаптер библиотеки W3xmlrpcClient использующий расширение CUrl для PHP
 *
 * @author Evgeny Blinov <e.a.blinov@gmail.com>
 * @license New BSD License
 * @link http://code.google.com/p/w3lib/
 * @package W3xmlrpcClient
 * @version $Id: W3xmlrpcAdapterCURL.php 5 2011-12-22 10:11:05Z E.A.Blinov@gmail.com $
 */

class W3xmlrpcAdapterCURL implements _W3xmlrpcAdapter{
    protected $handle;

    public    $repeatRequest = 0;
    public    $repeatPossible = array();

    protected function exec(){
        $i = 0;
        while (($ret = curl_exec($this->handle)) === false){
            if (
                (++$i > $this->repeatRequest) ||
                !in_array(curl_getinfo($this->handle, CURLINFO_HTTP_CODE), $this->repeatPossible)
            ) throw new W3xmlrpcClientException('Network error: '.curl_error($this->handle), curl_errno($this->handle));
            sleep(pow(2, $i));
        }
        return $ret;
    }

    public function setOptions(array $options){
        return curl_setopt_array($this->handle, $options);
    }

    public function __construct() {
        $this->repeatPossible = array(
            502 => 502,
            503 => 503,
            504 => 504
        );
        $this->handle = curl_init();
        $this->setOptions(array(
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_FAILONERROR => true,
            CURLOPT_ENCODING => '',
            CURLOPT_USERAGENT => W3xmlrpcClient::UA.' (Adapter '.__CLASS__.')'
        ));
    }
    public function __destruct() {
        curl_close($this->handle);
    }

    public function request($url, $request) {
        $this->setOptions(array(
            CURLOPT_URL => $url,
            CURLOPT_POSTFIELDS => $request,
            CURLOPT_COOKIEJAR  => '',
            CURLOPT_HTTPHEADER => array(
                'Content-Type: text/xml',
                'Content-Length: '.strlen($request)
            )
        ));
        return $this->exec();
    }
}